//
//  QQDetailVC.swift
//  QQ音乐
//
//  Created by  曹均华 on 16/6/4.
//  Copyright © 2016年 曹均华. All rights reserved.
//

import UIKit


// 专门放属性

class QQDetailVC: UIViewController {

    /** 做动画的 */
    @IBOutlet weak var lrcBackScrollView: UIScrollView!
  
    /** 前景图片 1 */
    @IBOutlet weak var foreImageView: UIImageView!
    /** 歌曲的总时长 1 */
    @IBOutlet weak var totalTimeLabel: UILabel!
    /** 背景图片 1 */
    @IBOutlet weak var backImageView: UIImageView!
    /** 歌曲名称 1 */
    @IBOutlet weak var songNameLabel: UILabel!
    /** 歌手名称 1 */
    @IBOutlet weak var singerNameLabel: UILabel!
    
    
    /** 歌词label n */
    @IBOutlet weak var lrcLabel: QQLrcLabel!
    /** 进度条 n */
    @IBOutlet weak var progressSlider: UISlider!
    /** 已经播放的时常 n */
    @IBOutlet weak var costTimeLabel: UILabel!
   
    
    
    /** 播放或者暂停按钮 待定 */
    @IBOutlet weak var playOrPauseBtn: UIButton!
    
    
    
  
    
    // 附加属性
    var timer: NSTimer?
    
    var displayLink: CADisplayLink?
    
    
    // 负责展示歌词的视图
//    var lrcView: UITableView?
    
    lazy var lrcTVC: QQLrcTVC = {
       
        return QQLrcTVC()
        
    }()
  
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}


// 数据展示
extension QQDetailVC {
    
    

    
    // 当歌曲切换时, 更新一次的情况
    func setUpOnce() -> () {
        
        let musicMM = QQMusicOperationTool.shareInstance.getNewMusicMessage()
        
        
        if musicMM.musicM?.icon != nil
        {
            /** 前景图片 1 */
            foreImageView.image = UIImage(named: (musicMM.musicM?.icon)!)
            /** 背景图片 1 */
            backImageView.image = UIImage(named: (musicMM.musicM?.icon)!)
        
        
        }
        
        /** 歌曲的总时长 1 */
        
        // 格式转换 234 -> 04:05
  
        
        totalTimeLabel.text =  musicMM.totalTimeFormat
        
        /** 歌曲名称 1 */
        songNameLabel.text = musicMM.musicM?.name
        /** 歌手名称 1 */
        singerNameLabel.text = musicMM.musicM?.singer
        
        
        // 重新刷新动画, 从头开始
        addRotation()
        
        if musicMM.isPlaying {
            resumeRotation()
        }else {
            pauseRotation()
        }
        
        // 更新一次数据源
        // 1. 获取歌词数据
        let lrcName = musicMM.musicM?.lrcname
        let lrcMs = QQMusicDataTool.getLrcMs(lrcName!)
//        print(lrcMs)
        // 2. 给lrctvc, 数据源 赋值
        lrcTVC.lrcMs = lrcMs
        
       
        
    }
    
    
    // 当歌曲切换时, 更新n次的情况
    // 1-> 1次
    func setUpTimes() -> () {
        
        
        let musicMM = QQMusicOperationTool.shareInstance.getNewMusicMessage()
        
        /** 进度条 n 1 秒一次 */
        progressSlider.value = Float(musicMM.costTime / musicMM.totalTime)
        
        /** 已经播放的时常 n 1 秒一次 */
        costTimeLabel.text = musicMM.costTimeFormat
        
        
        playOrPauseBtn.selected = musicMM.isPlaying
        
        /** 歌词label n 刷新频率最高 */
//        lrcLabel.text = nil
        
    }
    
    
    func addTimer() -> () {
        timer = NSTimer(timeInterval: 1, target: self, selector: #selector(setUpTimes), userInfo: nil, repeats: true)
        NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
    }
    
    func removeTimer() -> () {
        timer?.invalidate()
        timer = nil
    }
    
    
    // 更新歌, 频率非常高, 1s  60次
    
    func updateLrc() -> () {
        
         let musicMM = QQMusicOperationTool.shareInstance.getNewMusicMessage()
        let rowLrcM = QQMusicDataTool.getScrollRow(lrcTVC.lrcMs, currentTime: musicMM.costTime)
         lrcTVC.scrollRow = rowLrcM.row
        
        lrcLabel.text = rowLrcM.lrcM.lrcContent
        
        let lrcM = rowLrcM.lrcM
        let progress = (musicMM.costTime - lrcM.beginTime) / (lrcM.endTime - lrcM.beginTime)
        lrcLabel.progress = CGFloat(progress)
        
        // 获取到进度, 直接把进度, 给歌词展示控制器, 让它帮我展示进度
        lrcTVC.progress = CGFloat(progress)
        
        
        // 设置锁屏界面信息

        let state = UIApplication.sharedApplication().applicationState
        print(state.rawValue)
        if state == .Background {
            QQMusicOperationTool.shareInstance.setUpLockMessage()
        }
        
        
    }
    
    func addDisplayLink() -> () {
        displayLink = CADisplayLink(target: self, selector: #selector(updateLrc))
        displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
  
    }
    
    func removeDisplayLink() -> () {
        displayLink?.invalidate()
        displayLink = nil
    }
    
    
    
}


// 主要的业务逻辑
extension QQDetailVC {
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置界面
        addCustomSubView()
        
        // 监听播放完成的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(nextMusic), name: kPlayFinish, object: nil)
        
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 刷新界面
        setUpOnce()
        
        addTimer()
        addDisplayLink()
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        removeTimer()
        removeDisplayLink()
    }
    

    // 播放或者暂停当前歌曲
    @IBAction func playOrPause(sender: UIButton) {
        // 修改按钮播放状态
        sender.selected = !sender.selected
        
        if sender.selected {
//            print("播放")
            // 2. 播放
            QQMusicOperationTool.shareInstance.resumeCurrentMusic()
            
            // 旋转动画
            resumeRotation()
            
        }else {
//            print("暂停")
            QQMusicOperationTool.shareInstance.pauseCurrentMusic()
            
            // 暂停动画
            pauseRotation()
        }
        
    }
    
    // 上一首歌曲
    @IBAction func preMusic() {
       
        QQMusicOperationTool.shareInstance.preMusic()
        
        // 刷新界面
        setUpOnce()
    }
    
    // 下一首歌曲
    @IBAction func nextMusic() {
        QQMusicOperationTool.shareInstance.nextMusic()
        
        // 刷新界面
        setUpOnce()
    }
    
    // 关闭当前控制器
    @IBAction func close() {
        navigationController?.popViewControllerAnimated(true)
    }
    
    
    
    @IBAction func touchDown() {
        
        removeTimer()
        
    }
    
    @IBAction func touchUp() {
        
        addTimer()
        
        let musicMM = QQMusicOperationTool.shareInstance.getNewMusicMessage()
        
        // 根据进度条的值, 调整当前音乐的播放时间
        // 0 - 1
        let value = progressSlider.value
        let costTime = NSTimeInterval(value) * musicMM.totalTime
        QQMusicOperationTool.shareInstance.seekToTime(costTime)
        
    }
    
    @IBAction func valueChange() {
        
        let musicMM = QQMusicOperationTool.shareInstance.getNewMusicMessage()
        
        let value = progressSlider.value
        let costTime = NSTimeInterval(value) * musicMM.totalTime
        
        costTimeLabel.text = QQTimeTool.getFormatTime(costTime)
        
        
    }
    
    
}


// 界面操作
extension QQDetailVC {
    
    // 原则, 一定要把, 控件的添加, 和 控件的布局区分开
    // 控件的添加属于一次性的操作, 布局是可以多次

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // 专门用来布局的方法
        setCustomFrame()
    }
    
    
    // 主入口 - 1. 里面的代码执行, 只能执行一次
    func addCustomSubView() -> () {
        
        lrcBackScrollView.addSubview(lrcTVC.tableView)

        
        lrcBackScrollView.delegate = self
        lrcBackScrollView.pagingEnabled = true
        lrcBackScrollView.showsHorizontalScrollIndicator = false
        
        progressSlider.setThumbImage(UIImage(named: "player_slider_playback_thumb"), forState: UIControlState.Normal)
        
    }
    
    // 主入口- 2, 负责布局控件 里面的代码执行, 可以执行N次
    func setCustomFrame() -> () {
        lrcTVC.tableView?.frame = lrcBackScrollView.bounds
        lrcTVC.tableView?.x = lrcBackScrollView.width
        
        lrcBackScrollView.contentSize = CGSize(width: lrcBackScrollView.width * 2, height: 0)
        
        foreImageView.layer.cornerRadius = foreImageView.width * 0.5
        foreImageView.layer.masksToBounds = true

    }
    
 
    // 状态栏
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    
}

// 动画
extension QQDetailVC: UIScrollViewDelegate {
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // 1. 获取alpha
        print(scrollView.contentOffset.x)
    
        let alpha = 1 - scrollView.contentOffset.x / scrollView.width
        
        // 2. 拿到两个子控件, 修改透明度为某个值
        // 0   1
        lrcLabel.alpha = alpha
        foreImageView.alpha = alpha
        
    }
    
    
    func addRotation() -> () {
        
        // 添加旋转动画
        foreImageView.layer.removeAnimationForKey("rotate")
        let animation = CABasicAnimation(keyPath: "transform.rotation.y")
        animation.fromValue = 0
        animation.toValue = M_PI * 2
        animation.duration = 30
        animation.repeatCount = MAXFLOAT
        animation.removedOnCompletion = false
        
        foreImageView.layer.addAnimation(animation, forKey: "rotate")
        
    
    }
    
    func pauseRotation() -> () {
        
//        foreImageView.layer.removeAnimationForKey("rotate")
        foreImageView.layer.pauseAnimate()
        
    }
    

    func resumeRotation() -> () {
        foreImageView.layer.resumeAnimate()
    }
    
    
    
}



// 远程事件
extension QQDetailVC {
    
    override func remoteControlReceivedWithEvent(event: UIEvent?) {
        
        let subType = (event?.subtype)!
        
        switch subType {
        case .RemoteControlPlay:
            print("播放")
            QQMusicOperationTool.shareInstance.resumeCurrentMusic()
        case .RemoteControlPause:
            print("暂停")
            QQMusicOperationTool.shareInstance.pauseCurrentMusic()
        case .RemoteControlNextTrack:
            print("下一首")
            QQMusicOperationTool.shareInstance.nextMusic()
        case .RemoteControlPreviousTrack:
            print("上一首")
            QQMusicOperationTool.shareInstance.preMusic()
        default:
            print("buzhidao")
        }
        
        
        setUpOnce()
        
        
        
    }
    
    
    override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
         QQMusicOperationTool.shareInstance.nextMusic()
         setUpOnce()
    }
    
    
    
}



